// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Algo_Alert

//@version=5
indicator("🌊WaveTrend Z-Score [Algo Alert]")
n1 = input.int(10, minval = 1, title =  "Channel Length")
n2 = input.int(21, minval = 1, title = "Average Length")
Length = input.int(20, minval = 1)
StdDevs = input(2.0)
green = input.color(#0087ff, "Up Color") //#00ffbb
red = input.color(#ff8100, "Down Color") //#ff1100

ap = hlc3 
esa = ta.ema(ap, n1)
d = ta.ema(math.abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d)
tci = ta.ema(ci, n2)
 
////////////////////////// Z score
basis = ta.sma(tci, Length)
zscore = (tci - basis) / ta.stdev(tci, Length)
transcon = (zscore > StdDevs) or (zscore < -StdDevs) ? 0 : 55
fillcol = zscore > 0 ? color.new(green, transcon) : color.new(red, transcon)

z = plot(zscore, color = color.new(color.white, 100))
plot(StdDevs, color = color.new(red, 80))
plot(-StdDevs, color = color.new(green, 80))
mid = plot(0, color = color.gray)

fill(mid, z, zscore, 0, fillcol, color.new(chart.bg_color, 100))

plotchar(ta.crossover(zscore, -StdDevs) ? -StdDevs * 1.3 : na, char = "x", color = green, location = location.absolute, size = size.tiny)
plotchar(ta.crossunder(zscore, StdDevs) ? StdDevs * 1.3 : na, char = "x", color = red, location = location.absolute, size = size.tiny)